package cn.turboinfo.fuyang.api.provider.common.component.event

import cn.turboinfo.fuyang.api.entity.common.constant.EventConstants
import cn.turboinfo.fuyang.api.entity.common.event.WrapperApplicationEvent
import cn.turboinfo.fuyang.api.provider.rabbit.constant.RabbitConstants
import mu.KotlinLogging
import org.springframework.amqp.core.AmqpTemplate
import org.springframework.context.ApplicationListener
import org.springframework.stereotype.Component

@Component
class WrapperApplicationEventListener(
    private val rabbitTemplate: AmqpTemplate,
) : ApplicationListener<WrapperApplicationEvent> {

    private val logger = KotlinLogging.logger {}

    override fun onApplicationEvent(event: WrapperApplicationEvent) {
        runCatching {
            val topic = EventConstants.getTopicName(event.source.javaClass)

            rabbitTemplate.convertAndSend(
                RabbitConstants.ExchangeEvent,
                "${RabbitConstants.RoutingKeyEventPrefix}${topic}",
                event.source
            )
        }
            .onFailure {
                logger.error(it) { "发布事件消息出错" }
            }
    }

}